<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%@ page import="java.util.Date"%>
<% String formId = "form_" + new Date().getTime();
   String gridId = "grid_" + new Date().getTime();
   String path = request.getContextPath()+request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1);
%>
<script type="text/javascript" src="<%=request.getContextPath() %>/lib/uplodifyh5/event_common.js"></script>
<script type="text/javascript">
$(function (){
	var grid = $('[data-role="costSubGrid"]');
    var form = $("[name='costSubForm']");
    var selectItems = {"parcostCatecodeID":[{title:'请选择', value: ''}],"dccCodeID":[{title:'请选择', value: ''}],"isDetailID":[{title:'请选择', value: ''},{title:'是', value: '1'},{title:'否', value: '0'}]} ;
    var feeType = {"parcostCatecodeID":{},"dccCodeID":{}} ;
 	// 费用类别
 	if(diction.EXPENSE_TYPE) {
 		for(var i = 0 ; i<diction.EXPENSE_TYPE.length;i++) {
 	    	selectItems["parcostCatecodeID"].push({title:diction.EXPENSE_TYPE[i].DICDESC, value: diction.EXPENSE_TYPE[i].DICVALUE}) ;
 	    	feeType.parcostCatecodeID[diction.EXPENSE_TYPE[i].DICVALUE] = diction.EXPENSE_TYPE[i].DICDESC;
 	    }
 	} else {
 		selectItems["parcostCatecodeID"][0].title = "无数据" ;
 	}
    
    // 费用五大类
    if(diction.EXPENSE_TYPE_FIVE) {
    	for(var i = 0 ; i<diction.EXPENSE_TYPE_FIVE.length;i++) {
        	selectItems["dccCodeID"].push({title:diction.EXPENSE_TYPE_FIVE[i].DICDESC, value: diction.EXPENSE_TYPE_FIVE[i].DICVALUE}) ;
        	feeType.dccCodeID[diction.EXPENSE_TYPE_FIVE[i].DICVALUE] = diction.EXPENSE_TYPE_FIVE[i].DICDESC;
        }
    } else {
    	selectItems["dccCodeID"][0].title = "无数据" ;
    }
    
	PageLoader = {
			initSearchPanel:function(){
		    	// 费用类别
		    	form.find('#parcostCatecodeID').select({
					title: '请选择',
					contents: selectItems["parcostCatecodeID"]
			    }).on('change',function(){
			        form.find('#parcostCatecodeID_').val($(this).getValue());
			    }) 	   
			    // 费用五大类
		    	form.find('#dccCodeID').select({
					title: '请选择',
					contents: selectItems["dccCodeID"]
			    }).on('change',function(){
			        form.find('#dccCodeID_').val($(this).getValue());
			    }) 	    
			    // 是否费用明细
		    	form.find('#isDetailID').select({
					title: '请选择',
					contents: selectItems["isDetailID"]
			    }).on('change',function(){
			        form.find('#isDetailID_').val($(this).getValue());
			    }) 	    
			},
			initGridPanel: function(){
		         var self = this;
		         var width = 152;
		         return grid.grid({
		                identity:"costSubcode",
		                buttons: [
		                        {content: '<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-plus"><span>添加</button>', action: 'add'},
		                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-edit"><span>修改</button>', action: 'modify'},
		                        {content: '<button class="btn btn-danger" type="button"><span class="glyphicon glyphicon-remove"><span>删除</button>', action: 'delete'},
		                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-cloud-upload"><span>费用子类导入</button>', action: 'import'}
		                    ],
		                url:"${pageContext.request.contextPath}/CostSub/pageJson.dhc",
		                columns: 
	                	[
	                	 { title: '费用编码', name: 'costSubcode', width: width},
	                	 { title: '费用名称', name: 'costSubdesc', width: width},
	                	 { title: '费用别名', name: 'costSubAlias', width: width},
	     	             { title: '费用类别', name: 'parcostCatecode', width: width, render: function (rowdata, name, index) {
		                         return feeType.parcostCatecodeID[rowdata.parcostCatecode] ;
	                     	}
	                	 },
	     	             { title: '费用五大类', name: 'dccCode', width: width, render: function (rowdata, name, index) {
	                         	return feeType.dccCodeID[rowdata.dccCode] ;
	                     	}
	                	 },
	     	             { title: '是否费用明细', name: 'isDetail ', width: width, render: function (rowdata, name, index) {
	                         	return rowdata.isDetail == "1"? "是" :"否" ;
	                     	}
	                	 },
	     	             { title: '医嘱费用表编码', name: 'orderScode', width: width},
	     	             { title: '质控编码', name: 'costCodeQuality', width: width}
		                ]
		         }).on({
		                   'add': function(){
		                       self.add($(this));
		                   },
		                   'modify': function(event, data){
		                        var indexs = data.data;
		                        var $this = $(this);
		                        if(indexs.length == 0){
		                            drgUI.warning('请选择一条记录进行修改!');
		                            return;
		                        }
		                        if(indexs.length > 1){
		                             drgUI.warning('只能选择一条记录进行修改!');
		                            return;
		                        }
		                       self.modify(data.item[0],indexs[0], $this);
		                    },
		                   'delete': function(event, data){
		                        var indexs = data.data;
		                        var $this = $(this);
		                        if(indexs.length == 0){
		                            drgUI.warning('请选择要删除的记录!');
		                            return;
		                        }
		                        var remove = function(){
		                            self.remove(indexs, $this);
		                        };
		                        drgUI.confirm({
		                            content: '确定要删除所选记录吗?',
		                            callSure: remove
		                        });
		                   },
		                   'import' : function(event, data) {
								 $('#uploadifive-costSubImport input[type="file"]:last').click() ; 
							},
		         });
		    },
		    add: function(grid){
		        var self = this;
		        var dialog = $('<div class="modal fade"><div class="modal-dialog">'
		        	+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" '
		        	+'data-dismiss="modal" aria-hidden="true">&times;</button>'
		        	+'<h4 class="modal-title">新增</h4></div><div class="modal-body">'
		        	+'<p>One fine body&hellip;</p></div><div class="modal-footer">'
		        	+'<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>'
		        	+'<button type="button" class="btn btn-success" id="save">保存</button></div></div>'
		        	+'</div></div>');
		        $.get('<%=path%>/costSub-add.jsp').done(function(html){
		            dialog.modal({
		                keyboard:false
		            }).on({
		                'hidden.bs.modal': function(){
		                    $(this).remove();
		                }
		            }).find('.modal-body').html(html);
		            self.initPage(dialog.find('form'));
		        });
		        dialog.find('#save').on('click',{grid: grid}, function(e){
		              if(!Validator.Validate(dialog.find('form')[0],3))return;
		              var costSubcode = $("#costSubcodeID").val();
		              $.post('${pageContext.request.contextPath}/CostSub/isCostSubCodeExist.dhc',
		            		  {'costSubcode':costSubcode}).done(function(result){
	            			  if(result){
			            		  drgUI.error('费用编码已存在，请重新输入!');
			            	  } else {
			            		  $.post('${pageContext.request.contextPath}/CostSub/add.dhc', dialog.find('form').serialize()).done(function(result){
				   	                   if(result.success ){
				   	                        dialog.modal('hide');
				   	                        e.data.grid.data('koala.grid').refresh();
				   	                    	 drgUI.success('保存成功!');
				   	                    }else{
				   	                     	drgUI.error('保存失败,'+result.errorMessage);
				   	                    }
				   	              });
			            	  }
		               })
		        });
		    },
		    modify: function(item,id, grid){
		        var self = this;
		        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">修改</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
		        $.get('<%=path%>/costSub-update.jsp').done(function(html){
		               dialog.find('.modal-body').html(html);
		               self.initPage(dialog.find('form'));
		               dialog.find("#costSubcodeID").val($.trim(item.costSubcode));
		               dialog.find("#costSubdescID").val(item.costSubdesc);
		               dialog.find("#costSubAliasID").val(item.costSubAlias);
		               dialog.find("#parcostCatecodeID").setValue(item.parcostCatecode);
		               dialog.find("#dccCodeID").setValue(item.dccCode);
		               dialog.find("#orderScodeID").val(item.orderScode);
		               dialog.modal({
		                    keyboard:false
		               }).on({
		                    'hidden.bs.modal': function(){
		                        $(this).remove();
		                     }
		                });
		                dialog.find('#save').on('click',{grid: grid}, function(e){
		                dialog.find("#costSubcodeID").removeAttr("disabled");
		                if(!Validator.Validate(dialog.find('form')[0],3)) {
		                	dialog.find("#costSubcodeID").attr("disabled","disabled");
		                	return;
		                }
		  	            $.post('${pageContext.request.contextPath}/CostSub/add.dhc', dialog.find('form').serialize()).done(function(result){
	                        if(result.success){
	                            dialog.modal('hide');
	                            e.data.grid.data('koala.grid').refresh();
	                            drgUI.success('更新成功!');
	                        }else{
	                            drgUI.error(result.actionError);
	                        }
	                    });
		             });
		        });
		    },
		    initPage: function(form){
				form.find('.form_datetime').datetimepicker({
				     language: 'zh-CN',
				     format: "yyyy-mm-dd",
				     autoclose: true,
				     todayBtn: true,
				     minView: 2,
				     pickerPosition: 'bottom-left'
				 }).datetimepicker('setDate', new Date());//加载日期选择器
				 form.find('.select').each(function(){
				      var select = $(this);
				      var idAttr = select.attr('id');
				      select.select({
				          title: '请选择',
				          contents: selectItems[idAttr]
				      }).on('change', function(){
				          form.find('#'+ idAttr + '_').val($(this).getValue());
				      });
				 });
	    },
	    remove: function(ids, grid){
	    	var data = [{ name: 'costSubCodes', value: ids.join(',') }];
	    	$.post('${pageContext.request.contextPath}/CostSub/delete.dhc', data).done(function(result){
	            if(result.success){
	                grid.data('koala.grid').refresh();
	                drgUI.success('删除成功!');
	            }else{
	                drgUI.error('删除失败!');
	            }
	    	});
	    }
	} ;
	
	PageLoader.initSearchPanel();
	PageLoader.initGridPanel();
	
	// 下载按钮
	var downloadBtn = '<div class="btn-clickable">' ;
	downloadBtn+='<a href="download/costsub.rar" class="link text-sm" style = "text-decoration:none;color:#fff">' ;
	downloadBtn+='<i class="fa fa-download"></i>&nbsp;下载模版' ;
	downloadBtn+='</a>' ;
	downloadBtn+='</div>' ;
	$(<%=gridId%>).find("thead > tr > th").append(downloadBtn) ;
	
	
	form.find('#search').on('click', function(){
            if(!Validator.Validate(document.getElementById("<%=formId%>"),3))return;
            var params = {};
            form.find('input').each(function(){
                var $this = $(this);
                var name = $this.attr('name');
                if(name){
                    params[name] = $this.val();
                }
            });
            grid.getGrid().search(params);
        });
	
	
	// 费用子项插件初始化
    $('#'+tabId+' #costSubImport').uploadifive({
		'uploadScript' : contextPath + '/fileUpload/filesUpload.dhc',
        'height': 37,
        'width' :140,
        'auto'  : true,//是否自动开始
        'uploadLimit' : 10, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': false,  //是否完成后移除序列，默认为true
        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;费用子项上传',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){ },
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	  drgUI.error('文件上传失败！');
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error('浏览器检测不到兼容版本的HTML5！');
        }, 
        'onUpload': function(filesToUpload) {
        	$("#uploadifive-costSubImport-queue").css("display","none") ;
        },
        'onUploadError' : uploadify_onUploadError,
        'onQueueComplete':function(queueData){
        	$.post(contextPath+'/fileUpload/costSubImport.dhc').done(function(result){
        		var message = "" ;
        		if(result.success) {
        			message = result.data ;
        		} else {
        			message = result.errorMessage ;
        		}
        		drgUI.alert(message,function(){
        			$('[data-role="costSubGrid"]').grid('refresh');
        		});
        	});
        }
    });
 	$("#uploadifive-costSubImport").css("display","none") ;
 	
});

</script>
</head>
<body>
<div style="width:98%;margin-right:auto; margin-left:auto; padding-top: 15px;">

<!-- search form -->
<%-- <form name="costSubForm" id=<%=formId%> target="_self" class="form-horizontal">
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
    	<div class="form-group">
    		<label class="control-label" style="width:100px;float:left;">费用名称:&nbsp;</label>
            <div style="margin-left:15px;float:left;">
            	<input name="costSubDesc" class="form-control" type="text" style="width:180px;" id="costSubDescID"  />
			</div>
            <label class="control-label" style="width:100px;float:left;">费用类别:&nbsp;</label>
            <div style="margin-left:15px;float:left;">
            	<div class="btn-group select" id="parcostCatecodeID"></div>
	        	<input type="hidden" id="parcostCatecodeID_" name="parcostCatecode" />
        	</div>
        	<label class="control-label" style="width:100px;float:left;">费用五大类:&nbsp;</label>
            <div style="margin-left:15px;float:left;">
 				<div class="btn-group select" id="dccCodeID"></div>
	        	<input type="hidden" id="dccCodeID_" name="dccCode" />
 			</div>
        	<label class="control-label" style="width:100px;float:left;">是否费用明细:&nbsp;</label>
            <div style="margin-left:15px;float:left;">
 				<div class="btn-group select" id="isDetailID"></div>
	        	<input type="hidden" id="isDetailID_" name="isDetail" />
 			</div>
		</div>
	</td>
	<td style="vertical-align: bottom;"><button id="search" type="button" style="position:relative; margin-left:35px; top: -15px" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button></td>
  </tr>
</table>	
</form> --%>

<form name="costSubForm" id=<%=formId%> target="_self" class="form-horizontal">
	<div class="container-fluid">
		<div class="row">
			<div class="form-group col-md-3">
				<label>费用名称:&nbsp;</label>
	            <input name="costSubDesc" class="form-control" type="text" style="width:180px;" id="costSubDescID"  />
			</div>
			<div class="form-group col-md-3">
				 <label>费用类别:&nbsp;</label>
	             <div class="btn-group select" id="parcostCatecodeID"></div>
	        	 <input type="hidden" id="parcostCatecodeID_" name="parcostCatecode" />
			</div>
			<div class="form-group col-md-3">
				<label>费用五大类:&nbsp;</label>
	            <div class="btn-group select" id="dccCodeID"></div>
	        	<input type="hidden" id="dccCodeID_" name="dccCode" />
			</div>
			<div class="form-group col-md-3">
				<label>是否费用明细:&nbsp;</label>
	            <div class="btn-group select" id="isDetailID"></div>
	        	<input type="hidden" id="isDetailID_" name="isDetail" />
			</div>
			<div class="form-group col-md-1">
				<button id="search" type="button"  class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button>
			</div>
		</div>
	</div>
</form>
<!-- grid -->
<div data-role="costSubGrid" id=<%=gridId%>></div>
<!-- 费用子项导入 -->
<div><input id="costSubImport" type="file" name="costSubImport" style="display: none;"/></div>
</body>

</html>
